#!/bin/bash

# SpringCloud微服务部署脚本
# Author: daygods
# Date: 2025-07-11

echo "=== SpringCloud微服务部署脚本 ==="

# 设置变量
PROJECT_NAME="springcloud-demo"
BASE_DIR=$(cd "$(dirname "$0")"; pwd)
PROJECT_DIR=$(dirname "$BASE_DIR")
LOG_DIR="$PROJECT_DIR/logs"
PID_DIR="$PROJECT_DIR/pids"

# 创建必要的目录
mkdir -p "$LOG_DIR"
mkdir -p "$PID_DIR"

# 服务配置
declare -A SERVICES
SERVICES["eureka-service"]="8761"
SERVICES["gateway-service"]="8080"
SERVICES["user-service"]="8081"
SERVICES["order-service"]="8082"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $(date '+%Y-%m-%d %H:%M:%S') $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $(date '+%Y-%m-%d %H:%M:%S') $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $(date '+%Y-%m-%d %H:%M:%S') $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $(date '+%Y-%m-%d %H:%M:%S') $1"
}

# 检查Java环境
check_java() {
    if ! command -v java &> /dev/null; then
        log_error "Java未安装或未配置到PATH"
        exit 1
    fi
    
    JAVA_VERSION=$(java -version 2>&1 | awk -F '"' '/version/ {print $2}')
    log_info "Java版本: $JAVA_VERSION"
}

# 检查Maven环境
check_maven() {
    if ! command -v mvn &> /dev/null; then
        log_error "Maven未安装或未配置到PATH"
        exit 1
    fi
    
    MVN_VERSION=$(mvn -version | head -n 1)
    log_info "Maven版本: $MVN_VERSION"
}

# 构建项目
build_project() {
    log_info "开始构建项目..."
    cd "$PROJECT_DIR"
    
    if mvn clean package -DskipTests; then
        log_success "项目构建成功"
    else
        log_error "项目构建失败"
        exit 1
    fi
}

# 停止服务
stop_service() {
    local service_name=$1
    local pid_file="$PID_DIR/${service_name}.pid"
    
    if [ -f "$pid_file" ]; then
        local pid=$(cat "$pid_file")
        if ps -p "$pid" > /dev/null 2>&1; then
            log_info "停止服务: $service_name (PID: $pid)"
            kill "$pid"
            sleep 3
            
            if ps -p "$pid" > /dev/null 2>&1; then
                log_warn "强制停止服务: $service_name"
                kill -9 "$pid"
            fi
        fi
        rm -f "$pid_file"
    fi
}

# 启动服务
start_service() {
    local service_name=$1
    local port=${SERVICES[$service_name]}
    local jar_file="$PROJECT_DIR/$service_name/target/$service_name-1.0-SNAPSHOT.jar"
    local log_file="$LOG_DIR/${service_name}.log"
    local pid_file="$PID_DIR/${service_name}.pid"
    
    if [ ! -f "$jar_file" ]; then
        log_error "JAR文件不存在: $jar_file"
        return 1
    fi
    
    log_info "启动服务: $service_name (端口: $port)"
    
    nohup java -jar "$jar_file" \
        --spring.profiles.active=dev \
        --server.port="$port" \
        > "$log_file" 2>&1 &
    
    local pid=$!
    echo "$pid" > "$pid_file"
    
    sleep 5
    
    if ps -p "$pid" > /dev/null 2>&1; then
        log_success "服务启动成功: $service_name (PID: $pid)"
    else
        log_error "服务启动失败: $service_name"
        return 1
    fi
}

# 检查服务状态
check_service_status() {
    local service_name=$1
    local port=${SERVICES[$service_name]}
    local pid_file="$PID_DIR/${service_name}.pid"
    
    if [ -f "$pid_file" ]; then
        local pid=$(cat "$pid_file")
        if ps -p "$pid" > /dev/null 2>&1; then
            echo -e "${GREEN}✓${NC} $service_name (PID: $pid, Port: $port) - 运行中"
        else
            echo -e "${RED}✗${NC} $service_name - 已停止"
        fi
    else
        echo -e "${RED}✗${NC} $service_name - 未启动"
    fi
}

# 显示帮助信息
show_help() {
    echo "用法: $0 [选项]"
    echo "选项:"
    echo "  start     启动所有服务"
    echo "  stop      停止所有服务"
    echo "  restart   重启所有服务"
    echo "  status    查看服务状态"
    echo "  build     构建项目"
    echo "  deploy    构建并部署"
    echo "  help      显示帮助信息"
}

# 主函数
main() {
    case "$1" in
        "start")
            log_info "启动所有服务..."
            check_java
            for service in "${!SERVICES[@]}"; do
                start_service "$service"
            done
            ;;
        "stop")
            log_info "停止所有服务..."
            for service in "${!SERVICES[@]}"; do
                stop_service "$service"
            done
            ;;
        "restart")
            log_info "重启所有服务..."
            for service in "${!SERVICES[@]}"; do
                stop_service "$service"
            done
            sleep 2
            for service in "${!SERVICES[@]}"; do
                start_service "$service"
            done
            ;;
        "status")
            echo "=== 服务状态 ==="
            for service in "${!SERVICES[@]}"; do
                check_service_status "$service"
            done
            ;;
        "build")
            check_java
            check_maven
            build_project
            ;;
        "deploy")
            check_java
            check_maven
            build_project
            log_info "部署所有服务..."
            for service in "${!SERVICES[@]}"; do
                stop_service "$service"
            done
            sleep 2
            for service in "${!SERVICES[@]}"; do
                start_service "$service"
            done
            ;;
        "help"|"")
            show_help
            ;;
        *)
            log_error "未知选项: $1"
            show_help
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@"